package Login_Servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Cart_Function.Cart_Function;
import Cart_Utils.Cart;
import Login_Function.Login;

/**
 * Servlet implementation class Login_Servlet
 */
@WebServlet("/Login_Servlet")
public class Login_Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login_Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		HttpSession session = request.getSession(true);
		String UserName = (String) session.getAttribute("UserName");
		String name = new Login().login(request.getParameter("phone"), request.getParameter("password"));
		String uri[] = request.getHeader("Referer").split("/");
		
		if(name == null && UserName ==null){
			System.out.println("登录失败");
			session.setAttribute("IsLogin", "N");
		}else if(UserName==null){
			System.out.println("登录成功");
			session.setAttribute("IsLogin", "Y");
			session.setAttribute("UserName", name);
			ArrayList<Cart> carts = new Cart_Function().getUserCart(UserName);
			request.getSession().setAttribute("carts", carts);
		}
		if(uri[uri.length-1].endsWith("Servlet")){
			request.getRequestDispatcher("shop.jsp").forward(request, response);
		}else
			request.getRequestDispatcher(uri[uri.length-1]).forward(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
